package com.ocom.accesservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.accesservice.dao.IDaoMjDeviceInfo;
import com.ocom.accesservice.service.AreaInfoService;
import com.ocom.accesservice.service.MjDeviceInfoService;
import com.ocom.common.entity.access.EntityMjAreaInfo;
import com.ocom.common.entity.access.EntityMjDeviceInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.MachVo;
import com.ocom.common.vo.accessdevice.CenterMachInfoVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class MjDeviceInfoServiceImpl extends ServiceImpl<IDaoMjDeviceInfo, EntityMjDeviceInfo> implements MjDeviceInfoService {

    @Autowired
    AreaInfoService areaInfoService;


    @Autowired
    private IDaoMjDeviceInfo daoMjDeviceInfo;
    /**
     * 获取数量
     */
    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Override
    public Integer getCountByComId(Long companyId) {
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        return this.count(queryWrapper);
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Override
    public List<MachVo> getMachineListOnLoad(Long companyId) {
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        List<EntityMjDeviceInfo> list= this.list(queryWrapper);
        List<MachVo> resList=new ArrayList<MachVo>();
        for(EntityMjDeviceInfo entity: list){
            MachVo machVo=new MachVo();
            machVo.setMachId(entity.getDeviceId());
            machVo.setMachNo(entity.getDeviceNo());
            machVo.setMachName(entity.getDeviceName());
            machVo.setDateColor("black");
            machVo.setEndDate(entity.getEndTime());
            machVo.setLinkState(entity.getListState());
            machVo.setStateColor("404040");
            machVo.setPlace("");

            EntityMjAreaInfo entityMjAreaInfo= areaInfoService.getAreaInfoById(companyId,entity.getAreaId());

            if(entityMjAreaInfo!=null){
                machVo.setPlace("安装位置："+entityMjAreaInfo.getAreaName());
            }
            if(entity.getStatus()==1){
                machVo.setMachType(0L);
            }else{
                if(entity.getAreaId()==0){
                    machVo.setMachType(1L);
                }else{
                    machVo.setMachType(2L);
                }
            }


            resList.add(machVo);

        }
        return resList;
    }


    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Override
    public EntityMjDeviceInfo getMachineInfoByMachNo(Long companyId,String machNo){
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("device_no",machNo);
        queryWrapper.last("limit 1");
        EntityMjDeviceInfo entityMjDeviceInfo=this.getOne(queryWrapper);
        return entityMjDeviceInfo;
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Transactional
    @Override
    public EntityMjDeviceInfo updateMachNameByMachNo(Long companyId, String machNo, String machName) {
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("device_no",machNo);
        queryWrapper.last("limit 1");
        EntityMjDeviceInfo entityMjDeviceInfo=this.getOne(queryWrapper);
        if(entityMjDeviceInfo==null){
            return null;
        }
        entityMjDeviceInfo.setDeviceName(machName);
        this.updateById(entityMjDeviceInfo);
        return entityMjDeviceInfo;
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Transactional
    @Override
    public Result updateMachPlace(Long companyId, String machNo, Long areaNo) {
        QueryWrapper<EntityMjAreaInfo> areaInfoQueryWrapper=new QueryWrapper<>();
        areaInfoQueryWrapper.eq("area_id",areaNo);
        EntityMjAreaInfo areaInfo=areaInfoService.getOne(areaInfoQueryWrapper);
        //区域ID为0时是移除
//        if(areaInfo==null){
//            return ResultUtil.error(ResultEnum.Err_2015);
//        }
        QueryWrapper<EntityMjDeviceInfo>  queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("device_no",machNo);
        queryWrapper.last("limit 1");
        EntityMjDeviceInfo entityMjDeviceInfo=this.getOne(queryWrapper);
        if(entityMjDeviceInfo==null){
            return ResultUtil.error(ResultEnum.Err_2013);
        }
        if(entityMjDeviceInfo.getAreaId()==areaNo){
            return ResultUtil.error(ResultEnum.Err_2014);
        }
        entityMjDeviceInfo.setAreaId(areaNo);
        entityMjDeviceInfo.setListState(1L);
        entityMjDeviceInfo.setParaState(1L);
        entityMjDeviceInfo.setListAdd(-1L);
        entityMjDeviceInfo.setListDelete(-1L);
        entityMjDeviceInfo.setListDeleteTab(-1L);
        this.updateById(entityMjDeviceInfo);
        if(areaInfo==null){
            return ResultUtil.info(200,"出厂号为"+entityMjDeviceInfo.getDeviceNo()+"的设备已经转为备用机",null);
        }else{
            return ResultUtil.info(200,"出厂号为"+entityMjDeviceInfo.getDeviceNo()+"的设备已绑定到区域："+areaInfo.getAreaName(),areaInfo);
        }
      }

    /**
     * 移除设备 分库操作
     * @param companyId
     * @param machNo
     * @return
     */
    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Transactional
    @Override
    public EntityMjDeviceInfo removeMachPartDb(Long companyId, String machNo) {
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        queryWrapper.eq("device_no",machNo);
        queryWrapper.last("limit 1");
        EntityMjDeviceInfo entityMjDeviceInfo=this.getOne(queryWrapper);
        if(entityMjDeviceInfo!=null){
            this.removeById(entityMjDeviceInfo);
        }
        return entityMjDeviceInfo;
    }

    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    @Transactional
    @Override
    public void setDateZone(Long companyId) {
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("device_id");
        queryWrapper.eq("com_id",companyId);
        List<EntityMjDeviceInfo> list=this.list(queryWrapper);
        for (EntityMjDeviceInfo entityMjDeviceInfo : list) {
            EntityMjDeviceInfo eDeviceInfo=new EntityMjDeviceInfo();
            eDeviceInfo.setDeviceId(entityMjDeviceInfo.getDeviceId());
            eDeviceInfo.setZoneVer(DateUtil.getStrDate(new Date(), DateUtils.YYYYMMDDHHMMSS));
            updateById(eDeviceInfo);
        }
    }

    @Override
    public void updateMachTip(Long companyId, Long areaNo) {
        UpdateWrapper<EntityMjDeviceInfo> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.eq("area_id",areaNo);
        updateWrapper.set("list_state",1);
        updateWrapper.set("update_time",new Date());
        this.update(updateWrapper);
    }

    @Override
    public boolean downloadAll(Long companyId, Long machId) {
        UpdateWrapper<EntityMjDeviceInfo> updateWrapper=new UpdateWrapper<>();
        /**
         * 	mj_device_info .list_state=1
         * 			mj_device_info .list_add=-1
         * 			mj_device_info .list_add_tab=-1
         * 			mj_device_info .list_delete=-1
         * 			mj_device_info .list_delete_tab=-1
         */
        updateWrapper.eq("com_id",companyId);
        updateWrapper.eq("device_id",machId);
        updateWrapper.set("list_state",1);
        updateWrapper.set("list_add",-1);
        updateWrapper.set("list_add_tab",-1);
        updateWrapper.set("list_delete",-1);
        updateWrapper.set("list_delete_tab",-1);
        return this.update(updateWrapper);
    }


    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    public boolean canRemoveMach(Long companyId, String machNo) {
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        queryWrapper.eq("device_no",machNo);
        queryWrapper.last("limit 1");
        EntityMjDeviceInfo entityMjDeviceInfo=this.getOne(queryWrapper);
        if(entityMjDeviceInfo==null){
            return  false;
        }
        if(entityMjDeviceInfo.getAreaId().intValue()<=0){
            return  true;
        }else{
            return  false;
        }
    }

    // 更改设备参数状态（需下发）（setMachParaState）
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyId")
    @Override
    public void SetMachParaState(Long companyId, String machNo, String jobId, Long state) {
        QueryWrapper<EntityMjDeviceInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("com_id",companyId);
        wrapper.eq("device_no",machNo);
        EntityMjDeviceInfo deviceInfo = new EntityMjDeviceInfo();
        deviceInfo.setParaJobid(jobId);
        deviceInfo.setParaState(state);
        daoMjDeviceInfo.update(deviceInfo,wrapper);
    }

    @Override
    public void SetMachParaState(Long companyId, Long areaId, String jobId, Long state) {
        QueryWrapper<EntityMjDeviceInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("com_id",companyId);
        if (StringUtils.isNotNull(areaId)){
            wrapper.eq("area_id",areaId);
        }
        EntityMjDeviceInfo deviceInfo = new EntityMjDeviceInfo();
        deviceInfo.setParaJobid(jobId);
        deviceInfo.setParaState(state);
        daoMjDeviceInfo.update(deviceInfo,wrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB,companyId = "companyId")
    public CenterMachInfoVo getCommNumsByComId(Long companyId) {
        /**
         * select  count(device_no) as deviceNums  ,GROUP_CONCAT(device_no) as deviceNosfrom mj_device_info
         * where  com_id=@comId  and device_ver_type = 8  and status =2
         */
        QueryWrapper<EntityMjDeviceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("com_id",companyId);
        queryWrapper.in("device_ver_type",8);
        queryWrapper.eq("status",2);
        List<EntityMjDeviceInfo> list=this.list(queryWrapper);

        CenterMachInfoVo centerMachInfoVo=new CenterMachInfoVo();
        if(list!=null && list.size()>0){
            centerMachInfoVo.setComId(companyId);
            centerMachInfoVo.setDeviceNums(list.size());

            List<String> deviceNoList = list.stream().map(EntityMjDeviceInfo::getDeviceNo).collect(Collectors.toList());
            centerMachInfoVo.setDeviceNos(StringUtils.join(deviceNoList.toArray(),","));
        }

        return centerMachInfoVo;
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB)
    public boolean updateGroupVer(Long companyId) {
        UpdateWrapper<EntityMjDeviceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.set("group_ver", System.currentTimeMillis());
        return this.update(updateWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.PART_DB)
    public boolean updateZoneVer(Long companyId) {
        UpdateWrapper<EntityMjDeviceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("com_id",companyId);
        updateWrapper.set("zone_ver", System.currentTimeMillis());
        return this.update(updateWrapper);
    }

}
